package com.cjm.one.system.controller;

import com.cjm.one.common.result.Result;

import com.cjm.one.system.config.MinioService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URLEncoder;

@RestController
@RequestMapping("/admin/system/file")
@Tag(name = "文件管理")
@Slf4j
public class FileController {

    @Resource
    private MinioService minioService;

    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Operation(summary = "文件上传")
    public Result<String> uploadFile(
            @RequestPart("file") MultipartFile file,
            @RequestPart("category") String category
    ){
        try {
            log.info("上传文件: {},路径层级参数:{}", file.getOriginalFilename(),category);
            String objectName = minioService.uploadFile(file, minioService.SourceType_Admin,category);
            String fileUrl = minioService.getFileUrl(objectName);
            return Result.ok(fileUrl);
        } catch (Exception e) {
            log.error("上传失败: {}", e.getMessage());
            return Result.fail("文件上传失败");
        }
    }

    @GetMapping("/download/{objectName}")
    @Operation(summary = "文件下载")
    public void downloadFile(@PathVariable String objectName, 
                           HttpServletResponse response) {
        try (InputStream stream = minioService.downloadFile(objectName)) {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", 
                "attachment; filename=" + URLEncoder.encode(getFileName(objectName), "UTF-8"));
            
            IOUtils.copy(stream, response.getOutputStream());
            response.flushBuffer();
        } catch (Exception e) {
            log.error("下载失败: {}", e.getMessage());
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
    }

    // 从objectName中解析原始文件名
    private String getFileName(String objectName) {
        return objectName.substring(objectName.lastIndexOf("_") + 1);
    }
}
